import 'dart:math';

import 'package:bike_ride/common/mvvm/base_page.dart';
import 'package:bike_ride/common/util/account_manager.dart';
import 'package:bike_ride/common/util/format.dart';
import 'package:bike_ride/common/util/google_map_utils.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/widget/bottom_buttons.dart';
import 'package:bike_ride/common/widget/form_builder.dart';
import 'package:bike_ride/common/widget/gallery/pick_img_gallery.dart';
import 'package:bike_ride/common/widget/location_pin_widget.dart';
import 'package:bike_ride/common/widget/page_title_widget.dart';
import 'package:bike_ride/common/widget/xb_button.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/model/fault_report/view_model/fault_report_vm.dart';
import 'package:bike_ride/res/IconFont.dart';
import 'package:bike_ride/res/style/color_styles.dart';
import 'package:bike_ride/res/style/theme_styles.dart';
import 'package:bike_ride/router/navigator_util.dart';
import 'package:bike_ride/router/routers.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

import '../../../common/widget/circle_button_widget.dart';

/// 故障上报页面
class FaultReportView extends BaseStatefulPage<FaultReportViewModel> {
  final Map<String, dynamic>? arguments;

  const FaultReportView({this.arguments, super.key});

  @override
  FaultReportViewState createState() => FaultReportViewState();
}

class FaultReportViewState
    extends BaseStatefulPageState<FaultReportView, FaultReportViewModel> {
  int? expandId;
  final carNumberController = TextEditingController();
  final _textController = TextEditingController();
  List<String> imgUrl = [];
  List<String> selectedPartNames = [];

  @override
  void initAttribute() {
    if (widget.arguments?['vid'] != null) {
      carNumberController.text = widget.arguments?['vid'] ?? '';
    }
  }

  @override
  void initObserver() {}

  void notifyChange() {
    if (mounted) {
      setState(() {});
    }
  }

  Future startLocation() async {
    GoogleMapUtils.getCurrentPosition((position)async{
      final kGooglePlex = CameraPosition(
        target: LatLng(position.latitude, position.longitude),
        zoom: max(viewModel!.mapZoom, 18),
      );

      final GoogleMapController controller =
          await viewModel!.mapController.future;
      await controller
          .animateCamera(CameraUpdate.newCameraPosition(kGooglePlex));
    });
  }

  @override
  FaultReportViewModel viewBindingViewModel() {
    return FaultReportViewModel()..viewState = this;
  }

  @override
  Widget appBuild(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      backgroundColor: ColorStyles.color_F3F4F5,
      body: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          PageTitleWidget(title: S.current.feedback),
          Expanded(
            child: SingleChildScrollView(
              keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  _buildContainer1(),
                  _buildContainer2(),
                  _buildContainer3(),
                ],
              ),
            ),
          ),
        ],
      ),
      bottomNavigationBar: BottomButtons(
        hasRadius: true,
        child: XbButton(
          height: 96.rpx,
          width: MediaQuery.of(context).size.width -
              2 * ThemeStyles.pagePaddingHorizontal,
          onPressed: () async {
            if(carNumberController.text.trim().isEmpty){
              EasyLoading.showError(S.current.pleasePrintInCode);
              return;
            }else if(selectedPartNames.isEmpty){
              EasyLoading.showError(S.current.pleaseChoosePart);
              return;
            }
            EasyLoading.show();
            final result = await viewModel!.faultReportSubmit(
              place: selectedPartNames.join('|'),
              vid: carNumberController.text.trim(),
              lat: AccountManager.userLatitude,
              lng: AccountManager.userLongitude,
              imgurl: imgUrl,
              content: _textController.text.trim(),
            );
            if (result && mounted) {
              EasyLoading.showSuccess('success');
              NavigatorUtil.back(context);
            } else {
              EasyLoading.dismiss();
            }
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                S.current.confirmSubmit,
                style: TextStyle(
                    color: ColorStyles.color_FFFFFF, fontSize: 32.rpx),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildContainer1() {
    return Container(
      padding: EdgeInsets.symmetric(
          vertical: 20.rpx, horizontal: ThemeStyles.pagePaddingHorizontal),
      decoration: const BoxDecoration(
        color: ColorStyles.color_FFFFFF,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                IconFont.iconlocationCircle,
                size: 32.rpx,
                color: Theme.of(context).colorScheme.primary,
              ),
              SizedBox(
                width: 8.rpx,
              ),
              Flexible(
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 90.rpx),
                  child: Text(
                    S.current.confirmPart,
                    style: TextStyle(
                        fontSize: 32.rpx, fontWeight: FontWeight.bold),
                    maxLines: 2,
                  ),
                ),
              ),
            ],
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 20.rpx, horizontal: 10.rpx),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                ValueListenableBuilder(
                    valueListenable: viewModel!.address,
                    builder: (context, data, _) {
                      return ConstrainedBox(constraints: BoxConstraints(minHeight: 30.rpx),child: Text(
                        data,
                        style: TextStyle(
                            fontSize: 28.rpx, fontWeight: FontWeight.w500),
                      ),);
                    }),
                SizedBox(
                  height: 10.rpx,
                ),
                Text(
                  S.current.fixLocationTips,
                  style: TextStyle(fontSize: 24.rpx),
                )
              ],
            ),
          ),
          Container(
            width: MediaQuery.of(context).size.width -
                2 * ThemeStyles.pagePaddingHorizontal,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20.rpx),
            ),
            height: 300.rpx,
            child: Stack(
              children: [
                GoogleMap(
                  initialCameraPosition: CameraPosition(
                    target: LatLng(AccountManager.userLatitude!.toDouble(),
                        AccountManager.userLongitude!.toDouble()),
                    zoom: 18,
                  ),
                  myLocationEnabled: true,
                  trafficEnabled: true,
                  zoomControlsEnabled: false,
                  myLocationButtonEnabled: false,
                  markers: viewModel!.markers,
                  polygons: viewModel!.areaPolygons,
                  onMapCreated: (GoogleMapController controller) {
                    viewModel!.mapController.complete(controller);
                    startLocation();
                  },
                  onCameraMove: (CameraPosition position) {
                    viewModel!.getNearbyBike(
                        lat: position.target.latitude,
                        lng: position.target.longitude);
                  },
                  gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{
                    Factory<OneSequenceGestureRecognizer>(() => EagerGestureRecognizer()),
                  },
                ),
                const Center(
                  child: LocationPinWidget(),
                ),
                Positioned(
                  right: 28.rpx,
                  bottom: 28.rpx,
                  child: CircleButtonWidget(
                    path: 'assets/images/location.png',
                    onClick: () {
                      startLocation();
                    },
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildContainer2() {
    final placeholder = Image(
        image: const AssetImage("assets/common_v2/default_avatar_v2.png"),
        //头像占位图，加载过程中显示
        width: 142.rpx,
        height: 142.rpx);

    return Container(
      padding: EdgeInsets.symmetric(
          vertical: 20.rpx, horizontal: ThemeStyles.pagePaddingHorizontal),
      decoration: const BoxDecoration(
        color: ColorStyles.color_FFFFFF,
      ),
      margin: EdgeInsets.only(top: 20.rpx),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            height: 96.rpx,
            child: Row(
              children: [
                _e(),
                Text(
                  S.current.vehicleNumber,
                  style: TextStyle(
                      fontSize: 28.rpx, color: ColorStyles.color_333333),
                ),
                SizedBox(
                  width: 10.rpx,
                ),
                Expanded(
                  child: TextField(
                    controller: carNumberController,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: S.current.pleasePrintInCode,
                      hintStyle: TextStyle(
                          fontSize: 28.rpx, color: ColorStyles.color_999999),
                    ),
                  ),
                ),
                const Spacer(),
                IconButton(
                  onPressed: () {
                    NavigatorUtil.push(context, Routers.qrcodeScanPage)
                        .then((value) async {
                      final scanRul = value as String?;
                      var brandCode = decodeVidBrandCode(scanRul);
                      final result = await AccountManager.updateBrandCode(brandCode);
                      if(result){
                        var code = decodeEquipmentCode(scanRul);
                        carNumberController.text = code;
                      }
                    });
                  },
                  icon: Icon(
                    IconFont.iconVector2,
                    size: 32.rpx,
                    color: ColorStyles.color_333333,
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 20.rpx),
            child: Divider(height: 1.rpx, color: ColorStyles.color_E5E5E5),
          ),
          Row(
            children: [
              _e(),
              Text(
                S.current.pleaseSelectBike,
                style: TextStyle(
                    fontSize: 28.rpx,
                    color: ColorStyles.color_333333,
                    fontWeight: FontWeight.bold),
              ),
              Text(
                S.current.faultPart,
                style: TextStyle(
                    fontSize: 28.rpx,
                    color: Theme.of(context).colorScheme.primary,
                    fontWeight: FontWeight.bold),
              ),
            ],
          ),
          SizedBox(
            height: 500.rpx,
            child: GridView.count(
              crossAxisCount: 4,
              physics: const NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              mainAxisSpacing: 8.rpx,
              crossAxisSpacing: 8.rpx,
              childAspectRatio: 0.75,
              children: [
                for (int i = 0; i < viewModel!.serverParts.length; i++)
                  InkWell(
                    onTap: () {
                      final selectedName = viewModel!.serverParts[i].name;
                      if (selectedName == null || selectedName.isEmpty) return;

                      if (selectedPartNames.contains(selectedName)) {
                        selectedPartNames.remove(selectedName);
                      } else {
                        selectedPartNames.add(selectedName);
                      }
                      notifyChange();
                    },
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        ClipOval(
                          child: Container(
                            width: 142.rpx,
                            height: 142.rpx,
                            color: (selectedPartNames.contains(viewModel!.serverParts[i].name!))?Theme.of(context).colorScheme.primary:ColorStyles.color_E5E5E5,
                            child: Stack(
                              children: [
                                Center(
                                  child: ClipOval(
                                    child: CachedNetworkImage(
                                      imageUrl: viewModel!.serverParts[i].url!,
                                      width: 132.rpx,
                                      height: 132.rpx,
                                      fit: BoxFit.fill,
                                      placeholder: (context, url) => placeholder,
                                      errorWidget: (context, url, error) => placeholder,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),

                        Text(
                          viewModel!.serverParts[i].name!,
                          style: TextStyle(
                              fontSize: 24.rpx,
                              color: ColorStyles.color_333333),
                        )
                      ],
                    ),
                  )
              ],
            ),
          ),
          FormBuilder.buildXbFormTextArea(context,
              controller: _textController, hintText: S.current.otherWantAdd),
        ],
      ),
    );
  }

  Widget _buildContainer3() {
    return Container(
      padding: EdgeInsets.symmetric(
          vertical: 20.rpx, horizontal: ThemeStyles.pagePaddingHorizontal),
      decoration: const BoxDecoration(
        color: ColorStyles.color_FFFFFF,
      ),
      margin: EdgeInsets.symmetric(vertical: 20.rpx),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            S.current.submitPicTips,
            style: TextStyle(
                fontSize: 28.rpx,
                color: ColorStyles.color_333333,
                fontWeight: FontWeight.bold),
          ),
          SizedBox(
            height: 16.rpx,
          ),
          PickImgGallery(
            initList: imgUrl,
            maxCount: 4,
            width: 150.rpx,
            buttonColor: const Color(0xfff1f3f8),
            onChange: (List<String> list) {
              imgUrl = list;
            },
          ),
        ],
      ),
    );
  }

  Widget _e() {
    return Text(
      '*',
      style: TextStyle(fontSize: 32.rpx, color: ColorStyles.color_FF4D4F),
    );
  }
}
